package middleware

import (
	"encoding/json"
	"fmt"
	"github.com/valyala/fasthttp"
)

type middleware_t func(ctx *fasthttp.RequestCtx) (interface{}, error)

var MiddlewareList = []middleware_t{
	//CorsMiddleware,
	CheckTokenMiddleware,
}

func Use(next fasthttp.RequestHandler) fasthttp.RequestHandler {

	return fasthttp.RequestHandler(func(ctx *fasthttp.RequestCtx) {
		//If it's OPTIONS, set CORS headers and return
		if string(ctx.Method()) == "OPTIONS" {
			ctx.Response.Header.Set("Access-Control-Allow-Origin", "*")
			ctx.Response.Header.Set("Access-Control-Allow-Methods", "GET,POST,OPTIONS,DELETE,PUT")
			ctx.Response.Header.Set("Access-Control-Allow-Headers", "Accept,Accept-Encoding,Accept-Language,Cache-Control,Connection,Content-Length,Content-Type,D,T,Host,Origin,Referer,User-Agent,Pragma,X-Ca-Timestamp,X-Ca-Nonce,")
			ctx.Response.Header.Set("Access-Control-Expose-Headers", "Content-Length, Content-Range,Id")
			ctx.SetStatusCode(fasthttp.StatusOK)
			return
		}

		// Set CORS headers for non-OPTIONS requests
		ctx.Response.Header.Set("Access-Control-Allow-Origin", "*")
		ctx.Response.Header.Set("Access-Control-Allow-Methods", "GET,POST,OPTIONS,DELETE,PUT")
		ctx.Response.Header.Set("Access-Control-Allow-Headers", "Accept,Accept-Encoding,Accept-Language,Cache-Control,Connection,Content-Length,Content-Type,D,T,Host,Origin,Referer,User-Agent,Pragma,X-Ca-Timestamp,X-Ca-Nonce,")
		ctx.Response.Header.Set("Access-Control-Expose-Headers", "Id,Content-Length, Content-Range")

		for _, cb := range MiddlewareList {
			if body, err := cb(ctx); err != nil {
				fmt.Fprint(ctx, err)

				bytes, err := json.Marshal(body)
				if err != nil {
					ctx.SetBody([]byte(err.Error()))
					return
				}
				ctx.SetBody(bytes)
				return
			}
		}

		next(ctx)
	})
}
